import json
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from news_load import newsLoadInstance
import os
import smtplib
import datetime
import convert_to_html


# 邮件配置文件路径
CONFIG_FILE = "email_config.json"


def load_email_config():
    """从文件加载邮箱配置"""
    try:
        if os.path.exists(CONFIG_FILE):
            with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        else:
            return None
    except Exception as e:
        print(f"加载邮箱配置时出错: {e}")
        return None


def send_email(html_content):
    """发送 HTML 邮件"""
    try:
        # 读取配置
        config = load_email_config()
        print("加载配置文件成功，内容：" + str(config))
        if not config:
            print("邮件配置未找到，请先配置邮箱信息")
            return False

        # 创建邮件对象
        message = MIMEMultipart()
        # message['From'] = Header(f"新闻助手 <{config['sender']}>", 'utf-8')
        # 尝试只使用邮箱地址
        message['From'] = config['sender']
        message['To'] = Header(config['receiver'], 'utf-8')
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        subject = f'每日新闻导览 - {today}'
        message['Subject'] = Header(subject, 'utf-8')

        # 添加 HTML 正文
        html_body = MIMEText(html_content, 'html', 'utf-8')
        message.attach(html_body)

        # 连接 SMTP 服务器并发送邮件
        smtp = smtplib.SMTP(config['email_server'], config['email_port'])
        smtp.starttls()  # 启用 TLS 加密
        smtp.login(config['sender'], config['email_password'])
        smtp.sendmail(config['sender'], config['receiver'], message.as_string())
        smtp.quit()

        print("邮件发送成功！")
        return True

    except Exception as e:
        print(f"邮件发送失败: {e}")
        return False


def scheduler_send_news_report():
    """生成并发送新闻报告"""
    try:
        # 生成新闻报告
        newsLoadInstance.clear_data()
        filename = newsLoadInstance.run()

        # 生成适合邮件的 HTML 版本
        email_html_file = convert_to_html.convert_md_to_html_for_email(filename)

        # 读取 HTML 内容
        with open(email_html_file, 'r', encoding='utf-8') as f:
            html_content = f.read()

        # 发送邮件
        if os.path.exists(CONFIG_FILE):
            success = send_email(html_content)
            if success:
                print(f"[{datetime.datetime.now()}] 新闻报告已成功发送")
            else:
                print(f"[{datetime.datetime.now()}] 新闻报告发送失败")
        else:
            print("未找到邮件配置文件 email_config.json，跳过邮件发送")
    except Exception as e:
        print(f"发送新闻报告时出错: {e}")